package com.proyecto.core.vista.echo.componentes;

import java.util.ArrayList;
import java.util.List;

import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.ApplicationInstance;
import nextapp.echo2.app.Border;
import nextapp.echo2.app.Button;
import nextapp.echo2.app.Color;
import nextapp.echo2.app.Component;
import nextapp.echo2.app.Font;
import nextapp.echo2.app.Insets;
import nextapp.echo2.app.Label;
import nextapp.echo2.app.Style;
import nextapp.echo2.app.Table;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.app.layout.TableLayoutData;
import nextapp.echo2.app.table.DefaultTableModel;

import com.proyecto.core.Utilidades.UtilReflect;

import echopointng.BorderEx;
import echopointng.table.AbleTableSelectionModel;
import echopointng.table.DefaultPageableSortableTableModel;
import echopointng.table.PageableSortableTable;
import echopointng.table.SortableTableHeaderRenderer;
import echopointng.table.SortableTableModel;
import echopointng.table.SortableTableSelectionModel;
import echopointng.table.TableCellRendererEx;
import echopointng.xhtml.XhtmlFragment;

public class PSTabla{
	
	private List list;
	
	private DefaultTableModel dtm; 
	
	private DefaultPageableSortableTableModel pageableSortableTableModel;
	
	private SortableTableModel sortableTableModel ;
	
	private SortableTableSelectionModel sortableTableSelectionModel;
	
	private PageableSortableTable tabla ;
	
//	private PageableTableNavigation tableScroller;
	
	private ArrayList<String> campos = new ArrayList<String>();
	
	private ArrayList<String> titulos = new ArrayList<String>();
	
	private Object pojo = null;
	
	private ActionListener ManejarEvento = new ActionListener(){
		private static final long serialVersionUID = -3158157527012608210L;
		public void actionPerformed(ActionEvent e) {
			pojo = list.get(obtenerIndice((PageableSortableTable) e.getSource()));
		}
	};
	
	public  PSTabla(){
	}
	
	public PageableSortableTable generarTabla() {
		ColocarTitulos();
		tabla = new PageableSortableTable();
		tabla.setSelectionEnabled(true);
        tabla.setDefaultHeaderRenderer(this.headerTabla);//seteo el objeto a la tabla para que tenga el color del encabezado.
        tabla.addActionListener(ManejarEvento);
        tabla.setDefaultRenderer(Object.class,componentesTabla);
        tabla.setStyleName("OpenLabs.PageableSorTable.Default");
		return tabla;
	}

	public void ColocarTitulos(){
		dtm = new DefaultTableModel(this.getTitulos().size(),0);
		for (int k = 0; k < this.getTitulos().size(); k++) {
			dtm.setColumnName(k, this.getTitulos().get(k));
		}
	}
	
	public PageableSortableTable  cargarTabla(List l){
		pojo = null;
		this.list = l;
		ArrayList<String[]> al = new ArrayList<String[]>();
		try {
			al = ProcesarLista(l);
		} catch (Exception e1) {
//			e1.printStackTrace();
		}
		ColocarTitulos();
		
		dtm = LlenarTabla(titulos, al);
		pageableSortableTableModel = new DefaultPageableSortableTableModel(dtm);
		if (pageableSortableTableModel.getTotalRows() > 0){
			pageableSortableTableModel.setRowsPerPage(pageableSortableTableModel.getTotalRows());
		}
		AbleTableSelectionModel ableTableSelectionModel = new AbleTableSelectionModel(pageableSortableTableModel);
		ableTableSelectionModel.setSelectionMode(AbleTableSelectionModel.SINGLE_SELECTION);
        tabla.setModel(pageableSortableTableModel);
		tabla.setSelectionModel(ableTableSelectionModel);
        tabla.setSelectionEnabled(true);
        return tabla;
	}
	
	
	private TableCellRendererEx  componentesTabla = new TableCellRendererEx(){

		public XhtmlFragment getTableCellRendererContent(Table arg0, Object arg1, int column, int row) {
	          return null;
		}
		public boolean isActionCausingCell(Table arg0, int arg1, int arg2) {
			return false;
		}
		public Component getTableCellRendererComponent(Table tabla, Object contenido, int column, int row) {
		Label etiqueta = new Label(contenido != null ?(" "+contenido.toString()+" "):"");
		
		if (row % 2 == 0) {
			etiqueta.setStyleName("2OpenLabs.Label.Tabla.RowPar");
		} else {
			etiqueta.setStyleName("2OpenLabs.Label.Tabla.RowImpar");
		}
          return etiqueta;
		}
		public boolean isSelectionCausingCell(Table arg0, int arg1, int arg2) {
			// TODO Auto-generated method stub
			return false;
		}
		
	};
	
	private TableCellRendererEx  headerTabla = new TableCellRendererEx(){
		public XhtmlFragment getTableCellRendererContent(Table arg0, Object arg1, int column, int row) {return null;}
		public boolean isActionCausingCell(Table arg0, int arg1, int arg2) {return false;}
		
		public Component getTableCellRendererComponent(Table tabla, Object contenido, int column, int row) {
			SortableTableHeaderRenderer s = new SortableTableHeaderRenderer();
			try{
				Style estilo= ApplicationInstance.getActive().getStyle(Button.class, "2OpenLabs.btn.EncabezadoDeTabla");
				s.setBackground((Color)estilo.getProperty("background"));//color de fondo.
				tabla.setFont((Font)estilo.getProperty("font"));
				s.setBorder(new BorderEx(((Border)estilo.getProperty("border")).getSize().getValue(),((Border)estilo.getProperty("border")).getColor()));
				s.setInsets((Insets)estilo.getProperty("insets"));
				TableLayoutData tld = new TableLayoutData();
				tld.setAlignment((Alignment)estilo.getProperty("alignment"));
				tld.setInsets((Insets)estilo.getProperty("insets"));
				s.setLayoutData(tld);
			}catch (Exception e) {
				System.err.println("Se debe configurar el estilo apropiado en la hoja de estilo y llamarlo 2OpenLabs.btn.EncabezadoDeTabla");
			}
          return s.getTableCellRendererComponent(tabla, (contenido != null ?(contenido.toString()):""), column, row);
		}
		public boolean isSelectionCausingCell(Table arg0, int arg1, int arg2) {return false;}
	};
	
	
	public ArrayList<String[]> ProcesarLista(List lista) throws  Exception{
		ArrayList<String[]> a = new ArrayList<String[]>();
		Object atributo;
		//Recorro cada elemento de la lista
		for (int i = 0; i < lista.size(); i++) {
			String[] cam =new String[campos.size()];
			//Recorro cada uno de los campos del pojo
			for(int j = 0; j< campos.size(); j++){
				atributo= UtilReflect.invocarMetodoGet(lista.get(i), campos.get(j).toString(), null);
				//Meto en un arreglo los campos que corresponderan a cada fila de la tabla
				cam[j] = (atributo==null?"":atributo.toString());
			}
			//Adiciono la fila al arreglo con que se creara la tabla
			a.add(cam);
		}
		return a;
	}
	

	public Object ManejaEvento(ActionEvent e) {
		pojo = list.get(obtenerIndice((PageableSortableTable) e.getSource()));
		return pojo;
	}
	
	
	public DefaultTableModel LlenarTabla(ArrayList<String> titulos, ArrayList<String[]> lista) {
		for(int i = 0; i< lista.size();i++){
				dtm.addRow( lista.get(i));
		}
		return dtm;
	}
	
	public void incluirCampo(String titulo,String atributo) {
		campos.add(atributo);
		titulos.add(titulo);
	}

	public DefaultTableModel getDtm() {
		return dtm;
	}

	public int obtenerIndice(PageableSortableTable ps){
		String p=ps.getSelectionModel().toString();
		p = p.replace("(in model space)", "");
		p = p.replace(",", "");
		p= p.trim();
		return (Integer.parseInt(p));
	}
	
	public void setDtm(DefaultTableModel dtm) {
		this.dtm = dtm;
	}

	public ActionListener getManejarEvento() {
		return ManejarEvento;
	}

	public void setManejarEvento(ActionListener manejarEvento) {
		ManejarEvento = manejarEvento;
	}

	public DefaultPageableSortableTableModel getPageableSortableTableModel() {
		return pageableSortableTableModel;
	}

	public void setPageableSortableTableModel(
			DefaultPageableSortableTableModel pageableSortableTableModel) {
		this.pageableSortableTableModel = pageableSortableTableModel;
	}

	public SortableTableModel getSortableTableModel() {
		return sortableTableModel;
	}

	public void setSortableTableModel(SortableTableModel sortableTableModel) {
		this.sortableTableModel = sortableTableModel;
	}

	public SortableTableSelectionModel getSortableTableSelectionModel() {
		return sortableTableSelectionModel;
	}

	public void setSortableTableSelectionModel(
			SortableTableSelectionModel sortableTableSelectionModel) {
		this.sortableTableSelectionModel = sortableTableSelectionModel;
	}

	public PageableSortableTable getTabla() {
		return tabla;
	}

	public void setTabla(PageableSortableTable tabla) {
		this.tabla = tabla;
	}

	public Object getPojo() {
		return pojo;
	}

	public void setPojo(Object pojo) {
		this.pojo = pojo;
	}

	public ArrayList<String> getTitulos() {
		return titulos;
	}

	public void setTitulos(ArrayList<String> titulos) {
		this.titulos = titulos;
	}

	public List getList() {
		return list;
	}

	public void setList(List list) {
		this.list = list;
	}

	public ArrayList<String> getCampos() {
		return campos;
	}

	public void setCampos(ArrayList<String> campos) {
		this.campos = campos;
	}
}